package com.kamloo.stg.data.db;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class BookmarkDAO {
	private SQLiteDatabase m_database;
	private MySQLiteHelper m_dbHelper;
	public static final String TABLE_NAME 	 	 = "bookmark";
	public static final String COLUMN_ID 		 = "_id";
	public static final String COLUMN_NODE_ID 	 = "nodeId";
	private String[] m_allColumns = { COLUMN_ID, COLUMN_NODE_ID};
	
	public static final String TABLE_CREATE = 
			"CREATE TABLE " + 
		    TABLE_NAME + "(" + 
		    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + 
		    COLUMN_NODE_ID + " INTEGER NOT NULL);";
	
	public BookmarkDAO(Context context) {
		m_dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		m_database = m_dbHelper.getWritableDatabase();
	}

	public void close() {
		m_dbHelper.close();
	}
	
	/*
	public void add(Bookmark bookmark) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_ID, bookmark.getId());
		values.put(COLUMN_NODE_ID, bookmark.getNodeId());
		m_database.insert(TABLE_NAME, null, values);
	}
	*/
	
	public void add(int nodeId) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_NODE_ID, nodeId);
		m_database.insert(TABLE_NAME, null, values);
	}
	
	public void delete(int id) {
		System.out.println("Bookmark deleted with id: " + id);
		m_database.delete(TABLE_NAME, COLUMN_ID + " = " + id, null);
	}
	
	public Bookmark select(int nodeId) {
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, COLUMN_NODE_ID + " = " + nodeId, 
									  null, null, null, null);
		
		if (cur != null)
			cur.moveToFirst();
		
		Bookmark newBookmark = cursorToBookmark(cur);
		cur.close();
		return newBookmark;
	}
	
	public ArrayList<Bookmark> selectAll(){
		ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>();
		
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, 
				  					  null, null, null, null, null);

		if (cur != null) {
			cur.moveToFirst();
			while (!cur.isAfterLast()) {
				bookmarks.add(cursorToBookmark(cur));
				cur.moveToNext();
			}
		}

		cur.close();
		return bookmarks;
	}
	
	private Bookmark cursorToBookmark(Cursor cursor) {
		return new Bookmark(cursor.getInt(0),
							cursor.getInt(1));
	}
		
	public boolean isFavorite(int nodeId) {
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, 
									  COLUMN_NODE_ID + "=" + nodeId, 
									  null, null, null, null);
		
		return cur.getCount() != 0 ? true : false;
	}
	
}
